﻿using System;
using System.Collections.Generic;
using System.Xml.Linq;

namespace Jailu.AutoUpdater
{
    public class VersionDetails
    {
        public VersionDetails()
        {

        }

        public VersionDetails(string xml)
        {
            var element = XElement.Parse(xml);
            this.Version = element.Element("Version").Value;
            this.Desc = element.Element("Desc").Value;
            this.Files = this.LoadFiles(element.Element("Files"));
        }

        public string Version
        {
            get;
            internal set;
        }

        public string Desc
        {
            get;
            internal set;
        }

        public List<File> Files
        {
            get;
            internal set;
        }

        private List<File> LoadFiles(XElement element)
        {
            var files = new List<File>();

            foreach (var el in element.Elements("File"))
            {
                var file = new File()
                {
                    Name = el.Attribute("name").Value,
                    Path = el.Attribute("path").Value,
                    Version = el.Attribute("version").Value,
                    Size = Convert.ToInt64(el.Attribute("size").Value),
                    Url = el.Attribute("url").Value,
                };
                files.Add(file);
            }

            return files;
        }

        public void Save(string path)
        {
            XElement element = new XElement(
                "AutoUpdate", 
                new XElement("Version", this.Version),
                new XElement("Desc", this.Desc),
                new XElement(this.CreateFilesXElements())
            );

            element.Save(path);
        }

        private XElement CreateFilesXElements()
        {
            var element = new XElement("Files");

            foreach (var file in this.Files)
            {
                var el = new XElement("File");
                el.SetAttributeValue("path", file.Path);
                el.SetAttributeValue("name", file.Name);
                el.SetAttributeValue("version", file.Version);
                el.SetAttributeValue("size", file.Size);
                el.SetAttributeValue("url", "");

                element.Add(el);
            }

            return element;
        }
    }
}
